#include "Request.hpp"

using namespace BFT::messages;

/* The following constructor is for use ony by ReadOnlyRequest
   as it is designed to skip the order node entirely */
Request::Request(uint16_t _tag, uint32_t _sender, boost::shared_ptr<RequestCore> _pay, bool _b)
	:MacArrayMessage::MacArrayMessage(_tag, _pay->getTotalSize(), _sender, _b?EXECUTION_COUNT:FILTER_COUNT)

{
	
	uint32_t offset = getOffset();
	int core_bytes_size;
	boost::shared_ptr<char> coreBytes = _pay->getBytes(core_bytes_size);
	
	memcpy( (void*)(buffer.get()+offset) , (const void*)(coreBytes.get()) ,  core_bytes_size);
	
	core = _pay;
}

Request::Request(uint16_t _tag, uint32_t _sender, boost::shared_ptr<RequestCore> _pay)
	:MacArrayMessage::MacArrayMessage(_tag, _pay->getTotalSize(), _sender, ORDER_COUNT)
{	
	uint32_t offset = getOffset();
	int core_bytes_size;
	boost::shared_ptr<char> coreBytes = _pay->getBytes(core_bytes_size);
	
	memcpy(  (void*)(buffer.get()+offset) , (const void*)(coreBytes.get()) , core_bytes_size);
	
	core=_pay;

}

Request::Request(boost::shared_ptr<char> _bytes, int _bytes_size)
	:MacArrayMessage::MacArrayMessage(_bytes, _bytes_size)
{	
//	fprintf(stdout,"req constructor has been called. buffer_length:%d\n",_bytes_size);
	int offset= getOffset();
//	fprintf(stdout,"building a request. offset:%d, payload size:%d\n",offset,getPayloadSize());
	boost::shared_ptr<char> temp_buffer ((char*)malloc(getPayloadSize()),free);
	
	
	memcpy( (void*)(temp_buffer.get()) , (const void*)(buffer.get()+offset),  getPayloadSize());
	
	if (!FILTERED)
	{
		//boost::shared_ptr<SignedRequestCore> fake(new SignedRequestCore(temp_buffer, getPayloadSize()));// 
		core.reset(new SignedRequestCore(temp_buffer, getPayloadSize())); 
		//fprintf(stdout,"just to chack... command_size:%d\n",core.get()->getCommandSize());
	}	
	else
	{
		fprintf(stderr,"should not be here\n");
		exit(15);
	/*
		if (getTag() == CLIENT_REQUEST || getTag() == READ_ONLY_REQUEST)
			core.reset(new SimpleRequestCore(temp_buffer,getPayloadSize()));
		else
			core.reset(new FilteredRequestCore(temp_buffer,getPayloadSize()));
	*/
	}

}
	
boost::shared_ptr<RequestCore> Request::getCore()
{
	return core;
}
	
bool Request::equals(boost::shared_ptr<Request> _request)
{

	if ( (_request.use_count()==0) || !MacArrayMessage::equals(_request) )
		return false;
		
	return true;//core.get()->equals(_request.get()->core); 

}

void Request::printInfo()
{	
	MacArrayMessage::printInfo();
	fprintf(stdout,"Request information:\n");
	fprintf(stdout,"Nothing really interesting to say for Request...\n");
	core.get()->printInfo();	
}
